package cn.qin.xhangapi.controller.auth;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.map.MapUtil;
import cn.qin.xhangapi.util.redis.RedisUtil;
import cn.qin.xhangapi.util.response.ResponseResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RequestMapping("/api/auth")
@RestController
@CrossOrigin
public class CaptchaController {
    @Resource
    private RedisUtil redisUtil;

    //获取前端验证码
    @SaIgnore
    @GetMapping("/getCode")
    public ResponseResult getCode() {
        //生成前检查redis服务器中是否存在验证码
        if (redisUtil.hasKey("code")) {
            //如果存在，则删除
            redisUtil.del("code");
        }
        //定义图形验证码的长和宽
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        String base64 = lineCaptcha.getImageBase64();
        String code = lineCaptcha.getCode();
        //将验证码密码保存在Redis数据库中
        redisUtil.set("code", code, 180);
        return ResponseResult.success("获取验证码成功", MapUtil.builder().put("codeImg", base64).build());
    }
}
